layui.use(['table'], function() {
var table = layui.table,
    $ = layui.jquery,
    layer = layui.layer,
    form = layui.form,
    laytpl = layui.laytpl,
    message = parent.message;
var tableIns = table.render({
    elem: '#demo',
    height: 'full-132', //容器高度
    url: '../sys/businessdoc/list?_'+$.now(),
    where: {sidx: '', order: 'desc'},
    page: true,
    id: 'demo',
    limit: 20,
    cols: [
        [{
            checkbox: true,
            fixed: true
        }, {
            field: 'businessName',
            title: '业务名',
            width: 200,
            sort: true
        },
         {
            field: 'type',
            title: '布局类型',
            width: 250,
            templet: '#typetpl'
        },
         {
            field: 'typeId',
            title: '业务名',
            width: 350
        },
         {
            field: 'createTime',
            title: '创建时间',
            width: 350
        },{
            fixed: 'right',
            title: '操作',
            width: 300,
            align: 'center',
            toolbar: '#barDemo'
        }]
    ],
    done: function(res, curr, count) {
    	
    },
    loading: true,
});
//监听工具条
table.on('tool(demo)', function(obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
    var data = obj.data; //获得当前行数据
    var layEvent = obj.event; //获得 lay-event 对应的值
    var tr = obj.tr; //获得当前行 tr 的DOM对象

    if (layEvent === 'del') { //删除
        layer.confirm('确定删除该数据', function(index) {
            layer.close(index);
            //向服务端发送删除指令
            var ids = Array();
            ids.push(data.id);
            $.ajax({
        		type: "POST",
        	    url: "../sys/businessdoc/delete",
        	    data: JSON.stringify(ids),
        	    dataType: 'JSON',
        	    contentType: 'application/json',
        	    success: function(res){
        	    	if (res.code==0) {
        	        	message.show({
        	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
        	                msg:'操作成功'//提示信息
        	            });
        	        	obj.del(); //删除对应行（tr）的DOM结构
        	        	//tableIns.reload({where: {sidx: '', order: 'desc'}});
        	        } else {
        	        	layer.msg(res.msg, {icon: 2});
        	        }
        		}
        	});
        });
    } else if (layEvent === 'edit') { //编辑
    	$.get("../sys/businesssearch/info/"+data.type, function(res){
			if(res.code==0){
		    	$.get("../sys/basebusiness/select?type="+data.type, function(r){
				var d = {
						search:{
							id:data.id,
							businessName: data.businessName,
							isShow:data.isShow,
							type:data.type,
							typeId:data.typeId
						},
						types:r.list
		        };
		        laytpl($('#edit-tpl').html()).render(d, function(html) {
		            layer.open({
		                type: 1,
		                title: '修改评论',
		                content: html,
		                skin: 'layui-layer-rim', //加上边框
		                area: ['450px', '380px'],
		                btn: ['提交', '取消'],
		                yes: function(index, layero) {
		                    editIndex = index;
		                    $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
		                },
		                btn2: function(index, layero) {
		                	layer.close(index); //关闭弹出层
		                    $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
		                    return false;
		                },
		                success: function() {
		                    form.render(null, 'form-edit');
		                }
		            });
		            form.on('select(bjType)', function(data){
		            	$.get("../sys/basebusiness/select?type="+data.value, function(res){
		            		//d =[{id:1,name:'我十一'},{id:2,name:'我十2'}];
		            		//d2=[{id:1,name:'我十3'},{id:2,name:'我十4'}];
		            		d=res.list;
//		            		if(data.value==1){
//			            		  $("#typeId").html('');
//			            		  for(var i=0;i<d.length;i++){
//			            			  $("#typeId").append('<option value= '+d[i].id+'>'+d[i].name+'</option>');
//			            		  }
//			            	  }else{
			            		  $("#typeId").html('');
			            		  for(var i=0;i<d.length;i++){
			            			  if(data.value=='2'){
			            				  if(data.typeId==d[i].id){
			            					  $("#typeId").append('<option value= '+d[i].searchId+' selected>'+d[i].businessName+'</option>');
			            				  }
			            				  else{
			            					  $("#typeId").append('<option value= '+d[i].searchId+'>'+d[i].businessName+'</option>');
			            				  }
				            			  
			            			  }
			            			  else{
			            				  if(data.typeId==d[i].id){
					            			  $("#typeId").append('<option value= '+d[i].id+' selected>'+d[i].businessName+'</option>');
			            				  }
			            				  else{
					            			  $("#typeId").append('<option value= '+d[i].id+'>'+d[i].businessName+'</option>');
			            				  }

			            			  }
			            		  }
//			            	  }
		            		form.render('select'); //更新 lay-filter="bjContents" 所在容器内的全部 select 状态
		            	});
	            	});
		        });
		    });
			}else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		});
    }
});

$('.kit-search-btns').children('a').off('click').on('click', function() {
    var $that = $(this),
    action = $that.data('action');
    switch (action) {
        case 'add'://新增
        	$.get("../sys/basebusiness/select", function(r){
        	
			var d = {
					search:{
						id:'',
						businessName: '',
						isShow:'',
						type:'1',
						typeId:''
					},
					types:r.list
            };
            //渲染
            laytpl($('#edit-tpl').html()).render(d,
                function(html) {
                    layer.open({
                        type: 1,
                        title: '新增业务配置',
                        content: html,
                        skin: 'layui-layer-rim', //加上边框
                        area: ['450px', '380px'],
                        btn: ['提交', '取消'],
                        yes: function(index, layero) {
                            editIndex = index;
                            $('form[lay-filter="form-edit"]').find('button[lay-submit]').click();
                        },
                        btn2: function(index, layero) {
                        	layer.close(index); //关闭弹出层
                            $('form[lay-filter="form-edit"]').find('button[type="reset"]').click();
                            return false;
                        },
                        success: function() {
                            form.render(null, 'form-edit');
                        }
                    });
                    form.on('select(bjType)', function(data){
		            	$.get("../sys/basebusiness/select?type="+data.value, function(res){
		            		d=res.list;
			            		  $("#typeId").html('');
			            		  for(var i=0;i<d.length;i++){
			            			  if(data.value=='2'){
				            			  $("#typeId").append('<option value= '+d[i].searchId+'>'+d[i].businessName+'</option>');
			            			  }
			            			  else{
				            			  $("#typeId").append('<option value= '+d[i].id+'>'+d[i].businessName+'</option>');
			            			  }
			            		  }
//			            	  }
		            		form.render('select'); //更新 lay-filter="bjContents" 所在容器内的全部 select 状态
		            	});
	            	});
                });
        	});
            break;
        case 'del-bulk'://批量删除
            var d = table.checkStatus('demo');
            if (d.data.length === 0) {
                layer.msg('请选择要删除的数据');
                return;
            }
            var data = d.data,
                ids = [];
            layui.each(data, function(index, item) {
                ids.push(item.id);
            });
            layer.confirm('确定删除选中的数据', function(index) {
            	layer.close(index);
                //向服务端发送删除指令
                $.ajax({
            		type: "POST",
            	    url: "../sys/businessdoc/delete",
            	    data: JSON.stringify(ids),
            	    dataType: 'JSON',
            	    contentType: 'application/json',
            	    success: function(res){
            	    	if (res.code==0) {
            	        	message.show({
            	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
            	                msg:'操作成功'//提示信息
            	            });
            	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
            	        } else {
            	        	layer.msg(res.msg, {icon: 2});
            	        }
            		}
            	});
            });
            break;
        }
    });

var saveOrUpdate = function (datas) {
	var url = datas.id == null ? "../sys/businessdoc/save" : "../sys/businessdoc/update";
	$.ajax({
		type: "POST",
	    url: url,
	    data: JSON.stringify(datas),
	    dataType: 'JSON',
	    contentType: 'application/json',
	    success: function(res){
	    	if (res.code==0) {
	        	message.show({
	                skin:'default',//皮肤  支持:red,orange,cyan,blue,black,default
	                msg:'操作成功'//提示信息
	            });
	        	tableIns.reload({where: {sidx: '', order: 'desc'}});
	        } else {
	        	layer.msg(res.msg, {icon: 2});
	        }
		}
	});
}

form.render(null, 'kit-search-form');//初始化搜索表单
//监听搜索表单提交
form.on('submit(search)', function(data) {
	//带条件查询
    tableIns.reload({
    	where: {
    		sidx: '', order: 'desc',
    		businessName: data.field.businessName
    	}
    });
    return false;
});

var editIndex;
form.on('submit(formEdit)', function(data) {//监听表单提交
	var roleIds = Array();
	$("input:checkbox[name='roleIdList']:checked").map(function (index, elem) {
		roleIds.push($(elem).val());
		});
	data.field.roleIdList = roleIds;
	saveOrUpdate(data.field);
	editIndex && layer.close(editIndex); //关闭弹出层
    return false;
});

});
